<?php
require 'config.php';
// 引入 Composer 自动加载
require_once __DIR__ . '/vendor/autoload.php';
require_once 'login_check.php';
require_once 'manage_index.php';
check_admin_session();
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Exception as SpreadsheetException;

// 上传目录（需确保可写）
define('UPLOAD_DIR', __DIR__ . '/uploads/');
// 确保上传目录存在
if (!is_dir(UPLOAD_DIR)) {
    mkdir(UPLOAD_DIR, 0755, true);
}


// 处理Excel导入
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['import_excel'])) {
    // 校验文件上传
    if ($_FILES['excel_file']['error'] !== UPLOAD_ERR_OK) {
        echo "<script>alert('文件上传失败：{$_FILES['excel_file']['error']}');</script>";
        exit;
    }

    // 校验文件类型
    $allowedExt = ['xls', 'xlsx'];
    $ext = pathinfo($_FILES['excel_file']['name'], PATHINFO_EXTENSION);
    $allowedMime = [
        'application/vnd.ms-excel',
        'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    ];
    if (!in_array($ext, $allowedExt) || !in_array($_FILES['excel_file']['type'], $allowedMime)) {
        echo "<script>alert('仅支持 Excel 文件（.xls/.xlsx）');</script>";
        exit;
    }

    // 保存文件
    $fileName = uniqid() . '.' . $ext;
    $filePath = UPLOAD_DIR . $fileName;
    if (!move_uploaded_file($_FILES['excel_file']['tmp_name'], $filePath)) {
        echo "<script>alert('文件保存失败，请检查目录权限');</script>";
        exit;
    }

    // 读取并校验表头
    try {
        $spreadsheet = IOFactory::load($filePath);
        $sheet = $spreadsheet->getActiveSheet();
        $headerRow = $sheet->rangeToArray('A1:J1')[0];
        $expectedHeaders = [
            '学期开始时间',
            '学期结束时间',
            '值班日期',
            '周次',
            '值班干部',
            '值班员',
            '一区队值班员',
            '二区队值班员',
            '三区队值班员',
            '四区队值班员'
        ];
        if ($headerRow !== $expectedHeaders) {
            throw new Exception('Excel表头顺序或内容不符，请使用模板');
        }

        // 逐行解析
        $successCount = 0;
        $errorCount = 0;
        $errorMessages = [];
        $firstValidDate = null;

        for ($row = 2; $row <= $sheet->getHighestRow(); $row++) {
            $rowData = $sheet->rangeToArray("A{$row}:J{$row}", null, true, true, true)[$row];
            $data = [
                'start_time' => $rowData['A'],
                'finish_time' => $rowData['B'],
                'date' => $rowData['C'],
                'week' => $rowData['D'] ?: null,
                'duty_cadre' => $rowData['E'],
                'duty_officer' => $rowData['F'],
                'Duty_Officer_of_Squad_1' => $rowData['G'],
                'Duty_Officer_of_Squad_2' => $rowData['H'],
                'Duty_Officer_of_Squad_3' => $rowData['I'],
                'Duty_Officer_of_Squad_4' => $rowData['J'],
            ];

            // 数据校验
            try {
                foreach (['start_time', 'finish_time', 'date'] as $field) {
                    if (!strtotime($data[$field])) {
                        throw new Exception("第{$row}行「{$field}」日期格式错误（需Y-m-d）");
                    }
                }
                if (strtotime($data['start_time']) > strtotime($data['finish_time'])) {
                    throw new Exception("第{$row}行学期时间范围错误");
                }

                // 自动计算周次
                if (empty($data['week'])) {
                    if (!$firstValidDate) {
                        $firstValidDate = new DateTime($data['date']);
                    }
                    $currentDate = new DateTime($data['date']);
                    $diff = $currentDate->diff($firstValidDate);
                    $data['week'] = floor($diff->days / 7) + 1;
                }

                // 入库
                $sql = "INSERT INTO time_duty (
                    start_time, finish_time, week, duty_cadre, duty_officer, 
                    Duty_Officer_of_Squad_1, Duty_Officer_of_Squad_2, Duty_Officer_of_Squad_3, Duty_Officer_of_Squad_4, date
                ) VALUES (
                    :start_time, :finish_time, :week, :duty_cadre, :duty_officer, 
                    :Duty_Officer_of_Squad_1, :Duty_Officer_of_Squad_2, :Duty_Officer_of_Squad_3, :Duty_Officer_of_Squad_4, :date
                )";
                $stmt = $pdo->prepare($sql);
                if ($stmt->execute($data)) {
                    $successCount++;
                } else {
                    throw new Exception("第{$row}行数据入库失败");
                }
            } catch (Exception $e) {
                $errorCount++;
                $errorMessages[] = "第{$row}行：" . $e->getMessage();
            }
        }

        // 反馈结果
        $successMsg = $successCount ? "成功导入{$successCount}条" : '';
        $errorMsg = $errorCount ? "<br><br>❌ 失败详情：<br>" . implode("<br>", $errorMessages) : '';
        echo "<script>alert('{$successMsg}{$errorMsg}'); window.location.href='time_manage.php';</script>";

    } catch (Exception $e) {
        echo "<script>alert('导入失败：{$e->getMessage()}');</script>";
    }
    exit;
}

// 处理新增值班记录提交
// 新增 !isset($_POST['delete_id']) 条件，排除删除操作
if ($_SERVER['REQUEST_METHOD'] === 'POST' && !isset($_POST['import_excel']) && !isset($_POST['update_time_config']) && !isset($_POST['delete_id'])) {
    try {
        $startTime = $_POST['start_time'];
        $finishTime = $_POST['finish_time'];
        $date = $_POST['date'];
        if (!strtotime($startTime) || !strtotime($finishTime) || $startTime > $finishTime) {
            throw new Exception('请输入有效的日期范围（开始时间需早于结束时间）');
        }
        $week = $_POST['week'] ?: floor((strtotime($date) - strtotime($startTime)) / (60 * 60 * 24 * 7)) + 1;
        $sql = "INSERT INTO time_duty (
            start_time, finish_time, week, duty_cadre, duty_officer, 
            Duty_Officer_of_Squad_1, Duty_Officer_of_Squad_2, Duty_Officer_of_Squad_3, Duty_Officer_of_Squad_4, date
        ) VALUES (
            :start, :finish, :week, :cadre, :officer, :s1, :s2, :s3, :s4, :date
        )";
        $stmt = $pdo->prepare($sql);
        $stmt->execute([
            ':start' => $startTime,
            ':finish' => $finishTime,
            ':week' => $week,
            ':cadre' => $_POST['duty_cadre'],
            ':officer' => $_POST['duty_officer'],
            ':s1' => $_POST['squad1'],
            ':s2' => $_POST['squad2'],
            ':s3' => $_POST['squad3'],
            ':s4' => $_POST['squad4'],
            ':date' => $date
        ]);
    } catch (Exception $e) {
        echo "<script>alert('错误：" . addslashes($e->getMessage()) . "');</script>";
    }
}
// 处理删除请求
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_id'])) {
    try {
        $deleteId = $_POST['delete_id'];
        $sql = "DELETE FROM time_duty WHERE id = :id";
        $stmt = $pdo->prepare($sql);
        $stmt->execute([':id' => $deleteId]);
        echo "<script>alert('记录已删除！'); window.location.href='time_manage.php';</script>";
    } catch (Exception $e) {
        echo "<script>alert('删除失败：" . addslashes($e->getMessage()) . "');</script>";
    }
}
// 查询所有值班记录
$records = [];
try {
    $stmt = $pdo->query('SELECT * FROM time_duty ORDER BY id DESC');
    $records = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    echo "<script>alert('查询记录失败：" . addslashes($e->getMessage()) . "');</script>";
}


?>

<!DOCTYPE html>
<html>

<head>
    <title>值班安排</title>
    <meta charset="utf-8">
    <!-- 引入图标库（与其他管理界面保持一致） -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@mdi/font@7.4.47/css/materialdesignicons.min.css">
    <style>
    /* 基础布局样式（与其他管理界面统一） */
    body {
        font-family: "Microsoft YaHei", Arial, sans-serif;
        margin: 0;
        padding: 0;
        display: flex;
        min-height: 100vh;
        background: #f5f7fa;
    }
    
    /* 主内容区域（与侧边栏配合） */
    .main-content {
        margin-left: 240px; /* 与侧边栏宽度匹配 */
        width: 100%;
        padding: 48px 32px 32px 32px;
        box-sizing: border-box;
    }
    
    /* 浮框容器样式（统一浮框效果） */
    .manage-panel {
        max-width: 1000px;
        margin: 0 auto;
        background: #fff;
        border-radius: 16px;
        box-shadow: 0 4px 18px rgba(41, 128, 255, 0.08);
        padding: 32px;
    }

    /* 原有样式整合 */
    .message {
        padding: 12px;
        margin: 10px 0;
        border-radius: 4px;
        font-weight: bold;
    }
    .message.success {
        background-color: #d4edda;
        color: #155724;
        border: 1px solid #c3e6cb;
    }
    .message.error {
        background-color: #f8d7da;
        color: #721c24;
        border: 1px solid #f5c6cb;
    }

    .manage-container {
        width: 100%;
    }

    table {
        width: 100%;
        border-collapse: collapse;
        margin-top: 20px;
    }

    th,
    td {
        border: 1px solid #ddd;
        padding: 12px;
        text-align: left;
    }

    th {
        background-color: #f5f5f5;
        width: 18%;
    }

    .btn {
        padding: 4px 8px;         /*减小内边距*/
        font-size: 14px;          /* 减小字体大小 */
        background-color: #007bff;
        color: white;
        border: none;
        border-radius: 4px;
        cursor: pointer;
        margin-right: 5px; /* 减小右侧间距 */
        white-space: nowrap; /* 防止文字换行 */
    }

    .btn:hover {
        background-color: #0056b3;
    }

    .return-link {
        color: #007bff;
        text-decoration: none;
        display: inline-block;
        margin-top: 20px;
    }

    .config-form {
        background-color: #f0f0f0;
        padding: 15px;
        margin-bottom: 20px;
        border-radius: 8px;
    }

    .config-form label {
        margin-right: 15px;
    }

    .config-form input,
    .config-form select {
        padding: 6px;
        margin-right: 10px;
        border: 1px solid #ddd;
        border-radius: 4px;
    }

    .horizontal-form tr {
        vertical-align: middle;
    }

    .horizontal-form th {
        width: 120px;
    }

    /* 确保操作列按钮正确显示 */
    td form {
        width: 100%;
    }

    td .btn {
    margin-bottom: 5px; /* 仅保留垂直间距 */
    }

    /* 响应式适配（与其他管理界面同步） */
    @media (max-width: 900px) {
        .main-content {
            margin-left: 56px;
            padding: 24px 12px;
        }
        .manage-panel {
            padding: 16px;
        }
        .horizontal-form td {
            display: block;
            width: 100%;
            padding: 8px 0;
        }

        .horizontal-form input,
        .horizontal-form select {
            width: 100%;
        }
    }
    </style>
</head>

<body>
    <?php render_sidebar(); // 渲染侧边栏（与其他管理界面保持一致） ?>
    <div class="main-content">
        <div class="manage-panel">
            <div class="manage-container">
                <h2><span class="mdi mdi-calendar-clock"></span>值班安排</h2>
                <!-- 添加消息显示区域 -->
                <?php
                // 显示从编辑页传递的消息
                session_start();
                if (isset($_SESSION['message'])) {
                    $messageType = $_SESSION['messageType'] ?? 'error';
                    echo "<div class='message $messageType'>{$_SESSION['message']}</div>";
                    // 清除消息
                    unset($_SESSION['message'], $_SESSION['messageType']);
                }
                ?>

                <!-- Excel导入表单 -->
                <form action="time_manage.php" method="post" enctype="multipart/form-data" style="margin-bottom:20px;">
                    <input type="file" name="excel_file" accept=".xls,.xlsx" required>
                    <button type="submit" name="import_excel" class="btn" style="background-color:#17a2b8;">导入Excel</button>
                </form>

                <!-- 新增值班记录表单 -->
                <form method="post" class="horizontal-form">
                    <h3>新增值班记录</h3>
                    <table>
                        <tr>
                            <th>学期开始时间</th>
                            <td><input type="date" name="start_time" required id="start_time"></td>
                            <th>学期结束时间</th>
                            <td><input type="date" name="finish_time" required id="finish_time"></td>
                        </tr>
                        <tr>
                            <th>值班日期</th>
                            <td><input type="date" name="date" id="date" required></td>
                            <th>周次</th>
                            <td><input type="number" name="week" placeholder="自动计算" id="week"></td>
                        </tr>
                        <tr>
                            <th>值班干部</th>
                            <td><input type="text" name="duty_cadre" required></td>
                            <th>值班员</th>
                            <td><input type="text" name="duty_officer" required></td>
                        </tr>
                        <tr>
                            <th>一区队值班员</th>
                            <td><input type="text" name="squad1" required></td>
                            <th>二区队值班员</th>
                            <td><input type="text" name="squad2" required></td>
                        </tr>
                        <tr>
                            <th>三区队值班员</th>
                            <td><input type="text" name="squad3" required></td>
                            <th>四区队值班员</th>
                            <td><input type="text" name="squad4"></td>
                        </tr>
                        <tr>
                            <td colspan="4" style="text-align:center;">
                                <button type="submit" class="btn">添加</button>
                            </td>
                        </tr>
                    </table>
                </form>

                <hr>
                <h3>值班记录列表</h3>
                <table>
                    <tr>
                        
                        <th>学期开始时间</th>
                        <th>学期结束时间</th>
                        <th>值班日期</th>
                        <th>周次</th>
                        <th>值班干部</th>
                        <th>值班员</th>
                        <th>一区队值班员</th>
                        <th>二区队值班员</th>
                        <th>三区队值班员</th>
                        <th>四区队值班员</th>
                        <th>操作</th>
                    </tr>
                    <?php foreach ($records as $record): ?>
                    <tr>
                        
                        <td><?= $record['start_time'] ?></td>
                        <td><?= $record['finish_time'] ?></td>
                        <td><?= $record['date'] ?></td>
                        <td><?= $record['week'] ?></td>
                        <td><?= $record['duty_cadre'] ?></td>
                        <td><?= $record['duty_officer'] ?></td>
                        <td><?= $record['Duty_Officer_of_Squad_1'] ?></td>
                        <td><?= $record['Duty_Officer_of_Squad_2'] ?></td>
                        <td><?= $record['Duty_Officer_of_Squad_3'] ?></td>
                        <td><?= $record['Duty_Officer_of_Squad_4'] ?></td>
                        <td>
                            <a href="time_edit.php?id=<?= $record['id'] ?>" class="btn" style="background-color:#ffc107; color:black;">编辑</a>
                            <form method="post" onsubmit="return confirm('确定要删除这条记录吗？');">
                                <input type="hidden" name="delete_id" value="<?= $record['id'] ?>">
                                <button type="submit" class="btn" style="background-color:#dc3545;">删除</button>
                            </form>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </table>
            </div>
        </div>
    </div>
    <script>
        // 修复后
        const startTimeInput = document.getElementById('start_time');
        const dateInput = document.getElementById('date'); // 关联值班日期输入框
        const weekInput = document.getElementById('week');

        // 统一计算周次的函数
        function calculateWeek() {
        const startDate = new Date(startTimeInput.value);
        const dutyDate = dateInput.value ? new Date(dateInput.value) : new Date(); // 优先使用表单中的值班日期
    
        // 校验开始时间是否有效
        if (isNaN(startDate.getTime())) {
        weekInput.placeholder = '请先选择学期开始时间';
        return;
        }
    
        // 计算两个日期的差值（天）
        const diffTime = dutyDate - startDate;
        const diffDays = Math.floor(diffTime / (1000 * 60 * 60 * 24));
        // 确保周次至少为1
        const week = Math.max(Math.floor(diffDays / 7) + 1, 1);
        weekInput.placeholder = `自动计算值：${week}`;
        }

        // 监听开始时间和值班日期的变化，实时更新周次
        startTimeInput.addEventListener('change', calculateWeek);
        dateInput.addEventListener('change', calculateWeek);
    </script>
</body>
</html>
